package com.gsk.europepharma.salesReport.struts.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;

import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRAdmPdtDAO;
import com.gsk.europepharma.salesReport.utils.CodeLibelle;

public class ListeMarches extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String lib_orig = request.getParameter("lib_orig"); 
		
		// Liste des marches 
		tbSpBoSRAdmPdtDAO admPdtDao = new tbSpBoSRAdmPdtDAO();
		Session session = admPdtDao.getSession();
		Query req = session.getNamedQuery(tbSpBoSRAdmPdtDAO.QUERY_LISTE_MARCHES);
		req.setString("lib_orig", lib_orig);
		ArrayList result = new ArrayList(req.list());
		Iterator iter = result.iterator();
		List<CodeLibelle> marches = new ArrayList<CodeLibelle>();
		CodeLibelle marche;
		while (iter.hasNext()) {
			Object[] tmp = (Object[]) iter.next();
			marche = new CodeLibelle();
			marche.setCode(tmp[0].toString());
			marche.setLibelle(tmp[1].toString());
			marches.add(marche);
		}
		
		// Valeurs envoyees dans l'action 
		HashMap hm = new HashMap();
        hm.put("marches", marches);
        
        JSONObject json = JSONObject.fromObject(hm);

        response.addHeader("Content-Type", "application/json");
        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
        response.getOutputStream().flush();

		return null;
	}

}
